<?php

// +----------------------------------------------------------------------
// | SinianAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 祀念网络科技有限公司 [ http://www.sinianwork.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.sinianwork.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：
// | github 代码仓库：
// +----------------------------------------------------------------------

namespace app\index\controller;
use app\data\model\ControlPlanModel;
use think\Db;
use think\facade\Request;
use think\admin\Controller;

/**
 * 计划审核接口
 * Class index
 * @package app\index\controller
 */
class User extends Controller
{
    /**
     * 用户登陆
     */
    public function login()
    {
        $data = $this->_vali([
            'username.require' => '登录账号不能为空!',
            'username.min:4'   => '登录账号不能少于4位字符!',
            'password.require' => '登录密码不能为空!',
            'password.min:4'   => '登录密码不能少于4位字符!',
        ]);
        // 用户信息验证
        $map = ['is_deleted' => '0', 'username' => $data['username']];
        $user = Db::name('SystemUser')->where($map)->order('id desc')->find();
        if (empty($user)) $this->error('登录账号或密码错误，请重新输入!');
        // dump(md5(md5($user['password'] ).null));die;
        if ($user['password'] !== md5($data['password'])) {
            $this->error('登录账号或密码错误，请重新输入!');
        }
        if (empty($user['status'])) $this->error('账号已经被禁用，请联系管理员!');

        Db::name('SystemUser')->where(['id' => $user['id']])->update([
            'login_at' => Db::raw('now()'), 'login_ip' => Request::ip(), 'login_num' => Db::raw('login_num+1'),
        ]);
        $json = array(
            'id'=>$user['id'],
            'username'=>$user['username'],
            'phone'=>$user['phone'],
            'authorize'=>$user['authorize'],
            'parent_id'=>$user['parent_id'],
        );
        $this->success('ok',$json,1);
    }
    /**
     * 获取计划列表
     */
    public function getPlanApply(){
        $data = input('post.');
        if(!isset($data['admin_id']) || !$data['admin_id']) {
            $this->error('请先登陆');
        }
        $where[] = ['admin_id','eq',$data['admin_id']];
        if($data['admin_id'] == 10000){
            $where = array();
        }else{
            $where = array('admin_id'=>$data['admin_id']);
        }
        $where[] = ['deleted','eq',0];
        //搜索
        if(isset($data['plan_title'])){
            if(is_numeric($data['plan_title'])){
                $where[]=['id','like',$data['plan_title'].'%'];
            }else{
                $where[]=['plan_title','like','%'.$data['plan_title'].'%'];
            }
        }else{
            $where = [];
        }
        $planList = ControlPlanModel::where($where)->order('id desc')->limit(($data['page']-1)*$data['size'], $data['size'])->field('id,plan_title,is_deleted,plan_time,status,cate_id,plan_type,admin_name,admin_id')->select();
        $this->success('ok',$planList,1);

    }

    /**
     * 获取计划详情
     */
    public function getPlanInfo(){
        $data = input('post.');
        if(!$data['plan_id']) {$this->error('无此计划');}
        $where = array(
            'id'=>$data['plan_id']
        );
        $planList = ControlPlanModel::where($where)->find();
        $planList['plan_list'] = json_decode($planList['plan_list'],true);
        $this->success('ok',$planList,1);

    }
    /**
     * 获取物资列表
     */
    public function getCateList(){
        $data = input('post.');
        if(!isset($data['admin_id']) || !$data['admin_id']) {$this->error('请先登陆');}
        if(!isset($data['cate_id']) || !$data['cate_id']){$this->error('该分类不存在');}
        //搜索
        if(isset($data['material_code'])){
            if(is_numeric($data['material_code'])){
                $where[]=['material_code','like',$data['material_code'].'%'];
            }else{
                $where[]=['material_name','like','%'.$data['material_code'].'%'];
            }
        }else{
            $where = [];
        }
        //状态
        if(isset($data['status'])){
            $where[]=['status','eq',$data['status']];
        }
        if($data['cate_id'] == 1){
            $cateList = PlanApplyCateModel::where($where)->whereRaw('char_length(material_code) = 13')->limit(($data['page']-1)*$data['size'], $data['size'])->select();
        }elseif ($data['cate_id'] == 2) {
            $cateList = PlanApplyCate2Model::where($where)->whereRaw('char_length(material_code) = 13')->limit(($data['page']-1)*$data['size'], $data['size'])->select();
        }elseif ($data['cate_id'] == 3) {
            $cateList = PlanApplyCate3Model::where($where)->whereRaw('char_length(material_code) = 13')->limit(($data['page']-1)*$data['size'], $data['size'])->select();
        }
        return $this->success('ok',$cateList,1);
    }

    /**
     * 获取添加计划页面
     */
    public function getAddPlanList(){
        $data = input('post.');
        if(!$data['admin_id']){return $this->error('请先登陆');}
        $where['is_deleted'] = 0;
        // if(empty($data['authorize'])){
        //     $list['duizu_list'] = Db::name('system_user')->where('authorize','2')->where($where)->field('id,parent_id,username')->select();
        // }else{
        //     $list['duizu_list'] = Db::name('system_user')->where('id',$data['parent_id'])->where($where)->field('id,parent_id,username')->select();
        // }
        $list['keshi_list'] = Db::name('system_user')->where('authorize','2')->where($where)->field('id,parent_id,username')->select();
        $list['fenguan_list'] = Db::name('system_user')->where('authorize','3')->where($where)->field('id,parent_id,username')->select();
        $list['jingyi_list'] = Db::name('system_user')->where('authorize','4')->where($where)->field('id,parent_id,username')->select();
        $list['jingying_list'] = Db::name('system_user')->where('authorize','5')->where($where)->field('id,parent_id,username')->select();
        $list['kuangzhang_list'] = Db::name('system_user')->where('authorize','6')->where($where)->field('id,parent_id,username')->select();
        return $this->success('ok',$list,1);

    }

    /**
     * 获取上级信息
     */
    public function getParentInfo()
    {
        $id = input('id');
        $info = Db::name('system_user')->where(['id' => $id, 'is_deleted' => '0'])->value('parent_id');
        if($info == 0){return $this->success('ok',[],1);}
        $list = Db::name('system_user')->where(['id' => $info, 'is_deleted' => '0'])->field('id,parent_id,username')->select();
        return $this->error('ok',$list,1);

    }

    /**
     * 添加计划
     */
    public function addPlanApply(){
        $data = input('post.');
        if(!$data['admin_id']){return $this->error('请先登陆');}
        // if(!isset($data['duizu_id']) || empty($data['duizu_id'])){$this->error('请选择审核队干');}
        // if(!isset($data['keshi_id']) || empty($data['keshi_id'])){$this->error('请选择审核科室技术员');}
        // if(!isset($data['kezhang_id']) || empty($data['kezhang_id'])){$this->error('请选择审核科室科长');}
        // if(!isset($data['qiguan_id']) || empty($data['qiguan_id'])){$this->error('请选择企管科室技术员');}
        // if(!isset($data['qiguankz_id']) || empty($data['kezhang_id'])){$this->error('请选择企管科室科长');}
        // if(!isset($data['kuangdao_id']) || empty($data['kuangdao_id'])){$this->error('请选择矿级领导');}
        // if(!isset($data['jyfz_id']) || empty($data['jyfz_id'])){$this->error('请选择经营副总');}
        // if(!isset($data['max_id']) || empty($data['max_id'])){$this->error('请选择大矿长');}
        // if(!isset($data['gykz_id']) || empty($data['gykz_id'])){$this->error('请选择供应科长');}
        if(!isset($data['plan_list']) || empty($data['plan_list'])){$this->error('材料列表不可为空');}
        $data['jihuatime'] = date('Y-m-d',time());
        $plan_list = json_decode($data['plan_list'],true);
        foreach ($plan_list as $ks => $vs){
            if(!$vs['material_num'] || empty($vs['material_num'])){$this->error($vs['material_name'].'('.$vs['material_code'].')'.'数量不可为0');}
        }
        if(!isset($data['id'])){
            //添加

            //获取标题
            if($data['plan_type']){
                //获取计划时间
                $yuefen = date('m',time())+1;
                if($yuefen>12){
                    $nian = date('Y',time())+1;
                    $yuefen = 1;
                }else{
                    $nian = date('Y',time());
                }
                $title = $nian.'年'.$yuefen.'月（月度计划）';
                $data['plan_data_status'] = date('Ym',time())+1;
                //判断当月计划是否有提交过
                $wheres = array(
                    'plan_data_status'=>$nian.$yuefen,
                    'admin_id'=>session('admin_user')['id'],
                    'plan_type'=>1,
                );
                $isSubmit = PlanApplyModel::where($wheres )->value('status');
                if($isSubmit && $isSubmit['status'] != '-1'){
                    $this->error($nian.'年'.$yuefen .'月计划已提交，不可重复提交');
                }
            }else{
                //获取计划时间
                $yuefen = date('m',time());
                if($yuefen>12){
                    $nian = date('Y',time())+1;
                    $yuefen = 1;
                }else{
                    $nian = date('Y',time());
                }
                $title = $nian.'年'.$yuefen.'月（临时计划）';
                $data['plan_data_status'] = date('Ym',time());
                //判断当月临时计划是否已限制提交
                $wheres = array(
                    'plan_data_status'=>$nian.$yuefen,
                    'admin_id'=>session('admin_user')['id'],
                    'plan_type'=>0,
                );
                // $isSubmitCount = PlanApplyModel::where($wheres)->count();
                // if($isSubmitCount > 2){
                //     $this->error($nian.'年'.$yuefen .'当月临时计划提交次数已上限');
                // }
            }
            $data['plan_title'] = $title;
        }
        $data['cate_id'] = $data['cate_id'];
        //获取提交时间
        $data['plan_time'] = time();
        $data['plan_status'] = 2;
        $data['status'] = 0;
        //查询审核人信息
        if($data['plan_type']){
            $auth_auditing = [$data['keshi_id'],$data['fenguan_id'],$data['jingyi_id'],$data['kuangzhang_id']];
        }else{
            $auth_auditing = [$data['keshi_id'],$data['fenguan_id'],$data['jingyi_id'],$data['jingying_id'],$data['kuangzhang_id']];
        }
        // $auth_auditing = [$data['duizu_id'],$data['keshi_id'],$data['kezhang_id'],$data['qiguan_id'],$data['qiguankz_id'],$data['kuangdao_id'],$data['jyfz_id'],$data['max_id'],$data['gykz_id']];
        $userList = Db::name('system_user')->where(['is_deleted'=>0,'status'=>1])->whereIn('id',$auth_auditing)->field('id,username,authorize,nickname')->select();
        //开启事务
        Db::startTrans();
        try{

            //删除计划流程数据
            Db::name('auditing_plan_apply_time')->where('collect_id',$data['id'])->delete();
            // 数据添加
            $PlanApplyModel = new PlanApplyModel();
            if(!isset($data['id'])){
                // 生成计划ID
                $data['id'] = Data::uniqidNumberCode();
                $applyAll = $PlanApplyModel->insert($data);
            }else{
                $applyAll = $PlanApplyModel->where('id',$data['id'])->update($data);
            }
            if (!$applyAll) {throw new \Exception("服务器错误");}
            // 添加计划表流程数据
            $shenen = array();
            foreach ($userList as $ks=>$vs){
                $shenen[$ks]['collect_id'] = $data['id'];
                $shenen[$ks]['admin_id'] = $vs['id'];
                $shenen[$ks]['admin_name'] = $vs['username'];
                $shenen[$ks]['admin_authorize'] = $vs['authorize'];
            }
            $applyId = Db::name('auditing_plan_apply_time')->insertAll($shenen);
            // 判断是否添加成功
            if (!$applyId) {throw new \Exception("服务器错误");}

            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
        return $this->success('ok','',1);
    }

    /**
     * 获取计划流程
     */
    public function getPlanApplyProcedure(){
        $data = input('post.');
        if(!$data['admin_id']){return $this->error('请先登陆');}
        if(!isset($data['plan_id']) || !$data['plan_id']){return $this->error('该计划不存在');}
        $where = array(
            'collect_id'=>$data['plan_id']
        );
        $plan_list = Db::name('auditing_plan_apply_time')->where($where)->order('admin_authorize asc')->select();
        return $this->success('ok',$plan_list,1);

    }


    /**
     * 删除计划
     */
    public function deletePlanApply(){
        $data = input('post.');
        if(!$data['admin_id']){return $this->error('请先登陆');}
        if(!isset($data['plan_id']) || !$data['plan_id']){return $this->error('该计划不存在');}
        $where = array(
            'collect_id'=>$data['plan_id']
        );
        //开启事务
        Db::startTrans();
        try{
            //删除计划流程数据
            $plan = Db::name('auditing_plan_apply')->where('id',$data['plan_id'])->delete();
            if (!$plan) {throw new \Exception("服务器错误");}
            $plan_list = Db::name('auditing_plan_apply_time')->where('collect_id',$data['plan_id'])->delete();
            if (!$plan_list) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
        return $this->success('ok',[],1);

    }

    /**
     * 获取计划详情
     */
    public function getPlanApplyDetail(){
        $data = input('post.');
        if(!$data['admin_id']){return $this->error('请先登陆');}
        if(!isset($data['plan_id']) || !$data['plan_id']){return $this->error('该计划不存在');}
        $where = array(
            'is_deleted'=>0,
            'id'=>$data['plan_id']
        );
        $info = PlanApplyModel::where($where)->order('id desc')->find();
        $info['plan_list'] = json_decode($info['plan_list'],true);
        $info['total'] = 0;
        if($info['plan_list']){
            foreach ($info['plan_list'] as $v){
                $info['total'] += $v['material_xjprice'];
            }
        }else{
            $info['plan_list'] = [];
        }
        return $this->success('ok',$info,1);

    }

    /**
     * 获取计划审核列表
     */
    public function getToExamineList(){
        $data = input('post.');
        if(!$data['admin_id']){return $this->error('请先登陆');}
        if(!isset($data['authorize'])){return $this->error('权限不存在');}
        //搜索
        if(isset($data['material_code']) && $data['material_code']){
            if(is_numeric($data['material_code'])){
                $where[]=['id','like',$data['material_code'].'%'];
            }else{
                $where[]=['plan_title','like','%'.$data['material_code'].'%'];
            }
        }else{
            $where = [];
        }
        //权限重构
        $where[] = array( 'is_deleted','eq', 0);
        $where[] = array( 'plan_status','>=', $data['authorize']);

        if($data['authorize'] == 2){
            //队干
            $where[] = array('keshi_id','eq',$data['admin_id']);
        }elseif($data['authorize'] == 3){
            //科室技术员
            $where[] = array('fenguan_id','eq',$data['admin_id']);
        }elseif($data['authorize'] == 4){
            //科室科长
            $where[] = array('jingyi_id','eq',$data['admin_id']);
        }elseif($data['authorize'] == 5){
            //企管科技术员
            $where[] = array('jingying_id','eq',$data['admin_id']);
        }elseif($data['authorize'] == 6){
            //企管科长
            $where[] = array('kuangzhang_id','eq',$data['admin_id']);
        }elseif($data['admin_id'] == 10000){
            $where = [];
        }
        //状态
        if(isset($data['status'])){
            $where[]=['status','eq',$data['status']];
        }
        $list = Db::name('auditing_plan_apply')->where($where)->order('id desc')->limit(($data['page']-1)*$data['size'], $data['size'])->select();
        return $this->success('ok',$list,1);

    }

    /*
     * 备注(保管员权限)
     */
    public function remarks(){
        $index = input('index');
        $id = input('plan_id');
        $remarks = input('remarks');
        $info = PlanApplyModel::where('id',$id)->order('id desc')->find();
        $plan_list = json_decode($info['plan_list'],true);
        //重新组合json
        $plan_list[$index]['remarks'] = $remarks;
        $plan_json = json_encode($plan_list);
        $saveinfo = PlanApplyModel::where('id',$id)->update(['plan_list'=>$plan_json]);
        if($saveinfo === false){return $this->error('服务器错误');}
        return $this->success('数据更新成功');

    }


    /*
     * 数量/备注  日志添加
     */
    public function saveRemarks(){
        $id = input('plan_id');
        $index = input('index');
        $remarks = input('remarks');
        $number = input('numbers');
        $info = PlanApplyModel::where('id',$id)->order('id desc')->find();
        $plan_list = json_decode($info['plan_list'],true);
        $num = $plan_list[$index]['material_num'];
        // if($num < $number){return json(['code'=>400,'msg'=>'数量过大']);}
        //重新组合json
        $plan_list[$index]['material_num'] = $number;
        $plan_list[$index]['material_xjprice'] = round($number * $plan_list[$index]['material_price'],2);
        $plan_json = json_encode($plan_list);
        $saveinfo = PlanApplyModel::where('id',$id)->update(['plan_list'=>$plan_json]);
        if($saveinfo === false){return $this->error('服务器错误');}
        //添加日志
        $admin_id = input('admin_id');
        $username = input('username');
        $insetAll = array(
            'plan_id'=>$id,
            'remarks'=>$remarks,
            'key'=>$index,
            'original_num'=>$num,
            'save_num'=>$number,
            'admin_id'=>$admin_id,
            'admin_name'=>$username,
            'time'=>date('Y-m-d H:i:s',time())
        );
        Db::name('auditing_detati_log')->insertGetId($insetAll);
        return $this->success('数据更新成功');
    }




    /**
     * 审核通过
     */
    public function toResume()
    {
        $authorize = input('authorize');
        $user_id = input('admin_id');
        if(!$user_id){return $this->error('请先登陆');}
        $plan_id = input('plan_id');
        $planData = ControlPlanModel::where('id',$plan_id)->find();
        if($authorize >= 7 and $planData['plan_data_status'] != date('Ym',time())){
            if($planData['plan_type']){
                $this->error('月度计划请在次月审核');
            }else{
                $this->error('该临时计划已作废');
            }
        }
        $controlPlanItem = Db::name('sn_control_plan_time')->where('collect_id',$plan_id)->where('status',0)->order('admin_authorize asc')->column('admin_authorize');
        //开启事务
        Db::startTrans();
        try{
            if(isset($controlPlanItem[1]) and $controlPlanItem[1] > 0){
                $planInfo['plan_status'] = $controlPlanItem[1];
            }else{
                $planInfo['plan_status'] = $controlPlanItem[0];
                $planInfo['status'] = 1;
                //获取计划所属人
                $admin_id = ControlPlanModel::where('id',$plan_id)->value('admin_id');
                //创建库存表
                $sql = created_data('sn_enter_storehouse_'.$admin_id);
                Db::execute($sql);
                //获取计划子表数据
                $planList = ControlPlanListModel::where('plan_id',$plan_id)->field('material_code,material_name,material_model,material_unit,material_price,material_num')->column('material_code,material_name,material_model,material_unit,material_price,material_num','material_code');
                //添加个人库存数据
                $adminStorehouse = Db::name('sn_enter_storehouse_'.$admin_id)->whereIn('material_code',array_column($planList,'material_code'))->column('*','material_code');
                if(count($planList) == count($adminStorehouse)){
                    foreach ($planList as $k=>$v){
                        $planList[$k]['material_num'] = $v['material_num'] + $adminStorehouse[$k]['material_num'];
                    }
                    //先删除
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->whereIn('material_code',array_keys($planList))->delete();
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                    //新增数据
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->insertAll($planList);
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                }elseif (count($adminStorehouse) == 0){
                    //新增数据
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->insertAll($planList);
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                }else{
                    //比较两个数组的键名，并返回交集
                    $intersect_list = array_intersect_key($planList,$adminStorehouse);
                    foreach ($intersect_list as $k=>$v){
                        $intersect_list[$k]['material_num'] = $v['material_num'] + $adminStorehouse[$k]['material_num'];
                    }
                    //先删除
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->whereIn('material_code',array_keys($intersect_list))->delete();
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                    //比较两个数组的键名，并返回差集
                    $diffList = array_diff_key($planList,$adminStorehouse);
                    //合并数据
                    $mergeList = array_merge($intersect_list,$diffList);
                    //新增数据
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->insertAll($mergeList);
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                }
            }
            //主表数据修改
            $resut = ControlPlanModel::where('id',$plan_id)->update($planInfo);
            // 判断是否修改成功
            if (!is_int($resut)) {throw new \Exception("服务器错误");}
            // 流程数据修改
            $planTime = array('status'=>1,'time'=>date('Y-m-d H:i:s',time()));
            if($authorize == 6){
                $where = ['collect_id'=>$plan_id,'admin_authorize'=>6];
            }else{
                $where = ['collect_id'=>$plan_id,'admin_id'=>$user_id];
            }
//            $where = ['collect_id'=>$plan_id,'admin_id'=>$admin_user['id']];
            $applyTime = Db::name('sn_control_plan_time')->where($where)->update($planTime);
            if (!$applyTime) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('数据更新成功');
        //开启事务
        // Db::startTrans();
        // try{
        //     if ($authorize  == 10){
        //         //供应科科长
        //         $planInfo = array('status'=>1);
        //         //获取入库数据
        //         $plan_info = PlanApplyModel::where(['id'=>$plan_id,'is_deleted'=>0])->find();
        //         $plan_list = json_decode($plan_info['plan_list'],true);
        //         //创建库存表
        //         $sql = created_data('auditing_integration_'.$plan_info['admin_id']);
        //         Db::execute($sql);
        //         foreach ($plan_list as &$v){
        //             //更新库存
        //             $material_code = Db::name('auditing_integration_'.$plan_info['admin_id'])->where('material_code',$v['material_code'])->value('material_code');
        //             if($material_code){
        //                 $res = Db::name('auditing_integration_'.$plan_info['admin_id'])->where('material_code',$v['material_code'])->setInc('material_num',$v['material_num']);
        //             }else{
        //                 $inser = array(
        //                     'material_code'=> $v['material_code'],
        //                     'material_name'=> $v['material_name'],
        //                     'material_model'=> $v['material_model'],
        //                     'material_unit'=> $v['material_unit'],
        //                     'material_price'=> $v['material_price'],
        //                     'material_num'=> $v['material_num'],
        //                     'cate_id'=> $v['cate_id'],
        //                     'admin_id'=> $v['admin_id'],
        //                 );
        //                 //添加新数据
        //                 $res = Db::name('auditing_integration_'.$plan_info['admin_id'])->where('material_code',$v['material_code'])->insert($inser);
        //             }
        //             if(!is_int($res)){throw new \Exception("服务器错误");}
        //         }
        //     }else{
        //         $planInfo['plan_status'] = $authorize+1;
        //     }
        //     $resut = PlanApplyModel::where('id',$plan_id)->update($planInfo);
        //     // 判断是否修改成功
        //     if (!is_int($resut)) {throw new \Exception("服务器错误");}
        //     // 子表数据修改
        //     $planTime = array('status'=>1,'time'=>date('Y-m-d H:i:s',time()));
        //     $applyTime = Db::name('auditing_plan_apply_time')->where(['collect_id'=>$plan_id,'admin_id'=>$admin_id])->update($planTime);
        //     if (!$applyTime) {throw new \Exception("服务器错误");}
        //     // 执行提交操作
        //     Db::commit();
        // }catch(\Exception $e){
        //     // 回滚事务
        //     Db::rollback();
        //     // 获取提示信息
        //     $this->error($e->getMessage());
        // }
        // return $this->success('数据更新成功');
    }


    /**
     * 审核拒绝
     */
    public function toRefusal()
    {
        $username = input('username');
        $admin_id = input('admin_id');
        if(!$admin_id || !$username){return $this->error('请先登陆');}
        $plan_id = input('plan_id');
        $refusal_cause = input('refusal_cause');
        $dateTime = date('Y-m-d H:i:s',time());
        $planTime = array('status'=>-1,'time'=>$dateTime,'to_reason'=>$refusal_cause);
        //开启事务
        Db::startTrans();
        try{
            $resut = Db::name('auditing_plan_apply_time')->where(['collect_id'=>$plan_id,'admin_id'=>$admin_id])->update($planTime);
            if (!$resut) {throw new \Exception("服务器错误");}
            $plan_list = Db::name('auditing_plan_apply')->where('id',$plan_id)->update(['status' => '-1','reason_name'=>$username,'reason_id'=>$admin_id,'to_reason'=>$refusal_cause,'reason_time'=>$dateTime]);
            if (!$plan_list) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
        return $this->success('数据更新成功');
    }


    /**
     * 批量通过
     */
    public function batchPassRefusal()
    {
        $data = input('post.');
        if(!$data['admin_id']){return $this->error('请先登陆');}
        $idArr = explode(',',$data['plan_ids']);
        $admin_user = array(
            'authorize'=>$data['authorize'],
            'admin_id'=>$data['admin_id'],
        );
        $planInfo = array('plan_status'=>$admin_user['authorize']+1);
        //开启事务
        Db::startTrans();
        try{
            if($admin_user['authorize'] == 10){
                $planList = PlanApplyModel::whereIn('id',$idArr)->field('admin_id,plan_list,status,id,plan_status')->select();
                foreach ($planList as $ks=>$vs){
                    if($vs['status'] == 1 || $vs['plan_status'] > $admin_user['authorize']){
                        throw new \Exception("该计划已通过审核(".$vs['id'].")");die;
                    }
                    $plan_list = json_decode($vs['plan_list'],true);
                    //创建库存表
                    $sql = created_data('auditing_integration_'.$vs['admin_id']);
                    Db::execute($sql);
                    foreach ($plan_list as &$v){
                        //更新库存
                        $res = Db::name('auditing_integration_'.$vs['admin_id'])->where('material_code',$v['material_code'])->setInc('material_num',$v['material_num']);
                        if(!$res){
                            $inser = array(
                                'material_code'=> $v['material_code'],
                                'material_name'=> $v['material_name'],
                                'material_model'=> $v['material_model'],
                                'material_unit'=> $v['material_unit'],
                                'material_price'=> $v['material_price'],
                                'material_num'=> $v['material_num'],
                                'cate_id'=> $v['cate_id'],
                                'admin_id'=> $v['admin_id'],
                            );
                            //添加新数据
                            $res = Db::name('auditing_integration_'.$vs['admin_id'])->where('material_code',$v['material_code'])->insert($inser);
                        }
                        if(!is_int($res)){throw new \Exception("服务器错误");}
                    }
                }
                $planInfo['status'] = 1;
            }
            $resut = PlanApplyModel::whereIn('id',$idArr)->update($planInfo);
            // 判断是否修改成功
            if (!is_int($resut)) {throw new \Exception("服务器错误");}
            // 子表数据修改
            $planTime = array('status'=>1,'time'=>date('Y-m-d H:i:s',time()));
            $applyTime = Db::name('auditing_plan_apply_time')->where('admin_id',$admin_user['admin_id'])->whereIn('collect_id',$idArr)->update($planTime);
            if (!$applyTime) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        return $this->success('数据更新成功');
    }



    /**
     * 合并报表
     */
    public function mergePlan()
    {
        $data = input('post.');
        if(!$data['admin_id']){return $this->error('请先登陆');}
        if(!$data['authorize'] && $data['authorize'] != 4){return $this->error('无权限操作');}
        $idArr = explode(',',$data['plan_ids']);
        if(count($idArr) == 1){$this->error('请选择两个或两个以上合并');}
//        foreach ($info as &$v){
//            if($v['status'] != 1){$this->error('未通过审核计划不可合并');}
//            $plan_data_status[] = $v['plan_data_status'];
//        }
//        //去重plan_data_status
//        $res_m = array_unique($plan_data_status);
//        if(count($res_m)>1 ){$this->error('所选数据，提交的月份不统一');}
        $dateTime = date('Y-m-d H:i:s',time());
        $adminUser = array(
            'authorize'=>$data['authorize'],
            'username'=>$data['username'],
            'admin_id'=>$data['admin_id'],
        );
        $addAr = array(
            'plan_title'=>date('Y年m月d日',time()).'合并计划',
            'plan_ids'=>$data['plan_ids'],
            'merge_admin_id'=>$adminUser['admin_id'],
            'merge_admin_name'=>$adminUser['username'],
            'merge_time'=>$dateTime
        );
        //开启事务
        Db::startTrans();
        try{
            $plan_apply_merge_id = Db::name('auditing_plan_apply_merge')->insertGetId($addAr);
            if(!$plan_apply_merge_id){$this->error('服务器错误，请重试~');}
            $info = PlanApplyModel::where('id','in',$idArr)->field('id,status,plan_data_status,plan_list,plan_type')->select()->toArray();
            $new = array();
            foreach ($info as $key=>$val){
                //if($val['status'] != 1){$this->error('未通过审核计划不可合并');}
                $new_arr = json_decode($val['plan_list'],true);
                foreach ($new_arr as $k=>$v){
                    if(isset($new[$v['material_code']])){
                        $new[$v['material_code']]['material_num'] += $v['material_num'];
                        $new[$v['material_code']]['material_xjprice'] += $v['material_xjprice'];
                    }else{
                        $new[$v['material_code']]['merge_id'] = $plan_apply_merge_id;
                        $new[$v['material_code']]['admin_id'] = $adminUser['admin_id'];
                        $new[$v['material_code']]['material_code'] = $v['material_code'];
                        $new[$v['material_code']]['material_name'] = $v['material_name'];
                        $new[$v['material_code']]['material_model'] = $v['material_model'];
                        $new[$v['material_code']]['material_unit'] = $v['material_unit'];
                        $new[$v['material_code']]['material_price'] = $v['material_price'];
                        $new[$v['material_code']]['material_num'] = $v['material_num'];
                        $new[$v['material_code']]['material_xjprice'] = $v['material_xjprice'];
                        // $new[$v['material_code']]['plan_time'] = $v['plan_time'];
                    }
                }
            }
            sort($new);
            //子表数据添加
            $status = Db::name('auditing_plan_apply_merge_list')->insertAll($new);
            if(!$status){$this->error('服务器错误，请重试~');}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        return $this->success('数据合并成功');
    }
}
